package org.soenea.doitall.application;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.dsrg.soenea.service.SingleAppUniqueIdFactory;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.user.*;
import org.soenea.doitall.domain.model.user.mapper.*;

/**
 * Servlet implementation class UploadCVSPC
 */
public class UploadCVSPC extends SampleHttpServlet{
	private static final long serialVersionUID = 1L;

	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 50 * 1024;
	private int maxMemSize = 4 * 1024;
	private File file ;

	public void init( ){
		// Get the file location where it would be stored.
		filePath = 
				getServletContext().getInitParameter("file-upload"); 
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		isMultipart = ServletFileUpload.isMultipartContent(request);
		response.setContentType("text/html");
		java.io.PrintWriter out = response.getWriter( );
		if( !isMultipart ){
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet upload</title>");  
			out.println("</head>");
			out.println("<body>");
			out.println("<p>No file uploaded</p>"); 
			out.println("</body>");
			out.println("</html>");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File("c:\\temp"));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax( maxFileSize );

		try{ 
			// Parse the request to get file items.
			List fileItems = upload.parseRequest(request);

			// Process the uploaded file items
			Iterator i = fileItems.iterator();

			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet upload</title>");  
			out.println("</head>");
			out.println("<body>");
			while ( i.hasNext () ) 
			{
				FileItem fi = (FileItem)i.next();
				if ( !fi.isFormField () )	
				{
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					String contentType = fi.getContentType();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if( fileName.lastIndexOf("\\") >= 0 ){
						file = new File( filePath + 
								fileName.substring( fileName.lastIndexOf("\\"))) ;
					}else{
						file = new File( filePath + 
								fileName.substring(fileName.lastIndexOf("\\")+1)) ;
					}
					fi.write( file ) ;
					out.println("Uploaded Filename: " + fileName + "<br>");

					BufferedReader br = new BufferedReader(new FileReader(file.getPath()));
					try {
						User user;
						String username = "";
						String password = "";
						String firstName = "";
						String lastName = "";
						long UserID;

						String line = br.readLine();

						while (line != null) {
							String [] split = line.split(",");
							username = split[0];
							password = split[1];
							firstName = split[2];
							lastName = split[3];
							UserID = SingleAppUniqueIdFactory.getMaxId("user", "userID");
							user= new User(UserID,username,password,0,firstName,lastName,1,false);
							UoW.getCurrent().registerNew(user);

							line = br.readLine();
						}

					} finally {
						br.close();
						UoW.getCurrent().commit();
					}
				}
			}
			out.println("</body>");
			out.println("</html>");
		}catch(Exception ex) {
			System.out.println(ex);
		}
	}
}